package com.uroad.lib.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.webkit.GeolocationPermissions;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.uroad.lib.R;

import java.util.Timer;
import java.util.TimerTask;


public class ProgressWebView extends WebView {

	private ProgressBar progressbar;
	Context mcontext;

	public ProgressWebView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mcontext = context;
		progressbar = new ProgressBar(context, null,
				android.R.attr.progressBarStyleHorizontal);
		progressbar.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				5, 0, 0));

		Drawable drawable = context.getResources().getDrawable(
				R.drawable.progress_bar_states);
		progressbar.setProgressDrawable(drawable);
		addView(progressbar);
		setWebChromeClient(new WebChromeClient());
	}

	int beforeProgress = 0;
	int count = 0;
	Timer timer = new Timer();
	final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				if (count < 0) {
					timer.cancel();
					progressbar.setVisibility(GONE);
				}
			}
		}
	};

	TimerTask task = new TimerTask() {
		@Override
		public void run() {
			count--;
			progressbar.setProgress(beforeProgress++);
			Message message = new Message();
			message.what = 1;
			handler.sendMessage(message);
		}
	};

	public class WebChromeClient extends android.webkit.WebChromeClient {
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			if (newProgress == 100) {
				count = newProgress - beforeProgress;
				try {
					timer.schedule(task, 10, 5);
				} catch (Exception e) {
					progressbar.setVisibility(GONE);
				}

			} else {
				if (progressbar.getVisibility() == GONE)
					progressbar.setVisibility(VISIBLE);
				progressbar.setProgress(newProgress);
			}
			beforeProgress = newProgress;
			super.onProgressChanged(view, newProgress);
		}

		@Override
		public void onReceivedIcon(WebView view, Bitmap icon) {
			super.onReceivedIcon(view, icon);
		}

		@Override
		public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
			callback.invoke(origin, true, false);
			super.onGeolocationPermissionsShowPrompt(origin, callback);
		}
	}

	@Override
	protected void onScrollChanged(int l, int t, int oldl, int oldt) {
		LayoutParams lp = (LayoutParams) progressbar.getLayoutParams();
		lp.x = l;
		lp.y = t;
		progressbar.setLayoutParams(lp);
		super.onScrollChanged(l, t, oldl, oldt);
	}
}
